package org.zetaframework.controller.curd;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.zetaframework.annotation.log.SysLog;
import org.zetaframework.annotation.satoken.PreCheckPermission;
import org.zetaframework.annotation.satoken.PreMode;
import org.zetaframework.base.result.ApiResult;
import org.zetaframework.controller.BaseController;

import java.io.Serializable;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 基础删除 Controller
 *
 * @param <Entity> 实体
 * @param <Id>     主键字段类型
 * @author gcc
 */
public interface DeleteController<Entity, Id extends Serializable> extends BaseController<Entity> {

    /**
     * 单体删除
     *
     * @param id Id
     * @return ApiResult<Boolean>
     */
    @PreCheckPermission(value = {"{}:delete", "{}:remove"}, mode = PreMode.OR)
    @Operation(summary = "单体删除")
    @SysLog
    @DeleteMapping("/{id}")
    default ApiResult<Boolean> delete(@PathVariable @Parameter(description = "主键")Id id) {
        ApiResult<Boolean> result = handlerDelete(id);
        if (result.getDefExec()) {
            result.setData(getBaseService().removeById(id));
        }
        return result;
    }

    /**
     * 自定义单体删除
     *
     * @param id Id
     * @return ApiResult<Boolean>
     */
    default ApiResult<Boolean> handlerDelete(Id id) {
        return ApiResult.successDef();
    }

    /**
     * 批量删除
     *
     * @param ids List<Id>
     * @return ApiResult<Boolean>
     */
    @PreCheckPermission(value = {"{}:delete", "{}:remove"}, mode = PreMode.OR)
    @Operation(summary = "批量删除", description = """
    请求参数请使用【raw】类型
    
    请求示例 DELETE /user/batch
    [1,2,3]
    """)
    @SysLog
    @DeleteMapping("/batch")
    default ApiResult<Boolean> batchDelete(@RequestBody List<Id> ids) {
        // 转换为Set去重
        Set<Id> idSet = new HashSet<>(ids);

        ApiResult<Boolean> result = handlerBatchDelete(idSet);
        if (result.getDefExec()) {
            result.setData(getBaseService().removeByIds(idSet));
        }
        return result;
    }

    /**
     * 自定义批量删除
     *
     * @param ids Set<Id>
     * @return ApiResult<Boolean>
     */
    default ApiResult<Boolean> handlerBatchDelete(Set<Id> ids) {
        return ApiResult.successDef();
    }

}
